﻿package net.wangit.dev.unit;

import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.framework.util.QueryProcessor;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBImplementor;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;
import net.wangit.view.element.component.TextFieldElement;
import net.wangit.view.enumeration.EnumerationFactory;
import net.wangit.view.unit.UnitComponent;

public class FindElementUI implements UnitInterceptor {

	private static final String SQL = "select * from ELEMENT order by uid,eid";

	public FindElementUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		DB db = DBHelper.getDomainDB(ConsoleDomainUtil.getDomain(ac));
		UnitComponent uc = (UnitComponent) unit;
		String sql = QueryProcessor.addConditionAndOrder(ac,
				(DBImplementor) db, FindElementUI.SQL, "dev", uc
						.getQueryUnitId(), uc.getTableName(), null);
		unit.setData(db.query(sql));
		String columnName = ActionContextHelper.getRequest2Session(ac,
				"findelement.column", "dev.findelement.column", null);
		if (!Checker.isEmpty(columnName)) {
			MapList list = EnumerationFactory.getEnumeration(ac, "dev",
					"elementcolumn");
			int rowIndex = list.findRowIndex("value", columnName);
			TextFieldElement element = new TextFieldElement();
			element.setId(columnName);
			if (rowIndex >= 0)
				element.setName(list.getRow(rowIndex).get("name"));
			unit.addElement(element);
		}
		return unit.write(ac);
	}
}
